package com.example.multithread;

import lombok.SneakyThrows;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {

    public static void main(String[] args) throws InterruptedException {
        int threadCount = 3;
        CountDownLatch latch = new CountDownLatch(threadCount);

        for (int i = 0; i < threadCount; i++) {
            new Thread(new Worker(latch)).start();
        }

        System.out.println("Main thread is waiting for workers to finish...");
        // 主线程等待，直到 countDownLatch 的计数器变为 0
        latch.await();

        System.out.println("All workers are done, proceeding with main thread.");

        Thread.sleep(3000);
        System.out.println("===================");
    }

    static class Worker implements Runnable {
        private final CountDownLatch latch;

        Worker(CountDownLatch latch) {
            this.latch = latch;
        }

        @SneakyThrows
        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " is working...");
                Thread.sleep(1000);  // 模拟工作
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                // 完成工作后调用 countDown() 减少计数器
                Thread.sleep(5000);
                latch.countDown();
                System.out.println(Thread.currentThread().getName() + " finished work.");
            }
        }
    }

    private void lazyBindIfNecessary() {
        Thread bindThread = new Thread(){
            @Override
            public void run() {
                super.run();
            }
        };
    }
}
